package com.reflection1;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/24 13:16
 */

//反射性能测试
    //反射基本是解释执行，对执行速度有影响
public class ReflectSpeedTest {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        m1();
        m2();
        m3();

    }

    public static void m1(){

        Dog dog = new Dog();
        long start = System.currentTimeMillis();
        for(int i = 0; i < 100000000;i++){
            dog.hi();
        }
        long end = System.currentTimeMillis();
        System.out.println("使用对象.方法调用方法，耗时：" + (end - start));
    }

    public static void m2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        Class<?> cls = Class.forName("com.reflection1.Dog");
        Object o = cls.newInstance();
        Method methodHi = cls.getMethod("hi");
        long start = System.currentTimeMillis();
        for(int i = 0; i < 100000000;i++){
            methodHi.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("使用反射调用方法耗时：" + (end - start));
    }

    public static void m3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        Class<?> cls = Class.forName("com.reflection1.Dog");
        Object o = cls.newInstance();
        Method methodHi = cls.getMethod("hi");
        methodHi.setAccessible(false);
        long start = System.currentTimeMillis();
        for(int i = 0; i < 100000000;i++){
            methodHi.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("使用反射调用方法耗时(关闭安全访问检查)：" + (end - start));
    }
}
